<?php

namespace app\api\logic;

use think\Model;
use think\Db;
use think\Session;
use app\api\logic\UserLogic;
/**
 * 微信公众号的业务逻辑类
 */
class WechatLogic extends model
{
    private $appid = 'wxa5e230c798925e6e';
    private $appsecret = '0a775356ec6ae7ebb0000a9065d06205';

    //获取用户openid和用户信息
    public function get_openid($code)
    {
        $appid = $this->appid;
        $appsecret = $this->appsecret;
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
        $result = self::httpRequest($url);
        $jsoninfo = json_decode($result, true);
        if (empty($jsoninfo['openid']) || empty($jsoninfo['access_token'])) {
            return false;
        }
        $get_user_info = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $jsoninfo["access_token"] . '&openid=' . $jsoninfo["openid"] . '&lang=zh_CN';
        $userinfo = json_decode(self::httpRequest($get_user_info), true);
        if (empty($userinfo['nickname'])) {
            return false;
        }
        return $userinfo;
    }

    //获取用户信息
    public function get_user_info($openid)
    {
        $token = $this->get_token();
        $get_user_info = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $token . '&openid=' . $openid . '&lang=zh_CN';
        $userinfo = self::httpRequest($get_user_info);
        $userinfo = json_decode($userinfo, true);
        $data = array(
            'time' => time(),
            'even' => 4,
            'desc' => serialize($userinfo)
        );
        M('even')->insert($data);
        if (empty($userinfo['nickname'])) {
            return false;
        }
        return $userinfo;
    }

    //获取token
    public function get_token()
    {
        $token = UserLogic::get_session('token');
        if(!$token) {
            $appid = $this->appid;
            $appsecret = $this->appsecret;
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
            $res = self::httpRequest($url);
            $token = json_decode($res, true);
//        var_dump($token);die;
        $data = array(
            'time' => time(),
            'even' => 6,
            'desc' => serialize($token)
        );
        M('even')->insert($data);
            if (empty($token['access_token'])) {
                return false;
            }
            UserLogic::set_session('token',$token['access_token'],7200);
            return $token['access_token'];
        }else{
            return $token;
        }

    }

    //获取二维码
    public function get_qrcode($id)
    {
        $token = $this->get_token();
//        var_dump($token);die;
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$token}";
        $post = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": {$id}}}}";
        $res = self::httpRequest($url, $post);
        $res = json_decode($res, true);
        if (empty($res['ticket'])) {
            return false;
        }
        //换取二维码
        $url1 = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($res['ticket']);
        $img = self::httpRequest($url1);
        //打开图片资源
        $code_img = imagecreatefromstring($img);
        //保存图片
        $path = ROOT_PATH . 'public/qrcode/';
        $name = $id . '.png';

        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        } elseif (!file_exists($path . $name)) {
            imagepng($code_img, $path . $name);
        }
        return 'http://' . $_SERVER['HTTP_HOST'] . '/qrcode/' . $name;
    }

    static function httpRequest($url, $postData = array())
    {
        // （1）初始化
        $ch = curl_init();
        // （2）设置选项
        // 设置请求的url
        curl_setopt($ch, CURLOPT_URL, $url);
        // 将curl_exec()获取的数据以字符串返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if (!empty($postData)) {
            // 设置请求方式为post
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        }
        //curl注意事项，如果发送的请求是https，必须要禁止服务器端校检SSL证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        // （3）执行
        $result = curl_exec($ch);
        // （4）关闭
        curl_close($ch);
        return $result;
    }

    public function responseMsg()
    {
        $postStr = file_get_contents("php://input");
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            switch ($RX_TYPE) {
                case "text":
                    $resultStr = $this->handleText($postObj);
                    break;
                case "event":
                    $resultStr = $this->handleEvent($postObj);
                    break;
                default:
                    $resultStr = false;
                    break;
            }
            return $resultStr;
        } else {
            return false;
        }
    }

    public function handleText($postObj)
    {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        if (!empty($keyword)) {
            $msgType = "text";
            $contentStr = "Welcome to wechat world!";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        } else {
            echo "Input something...";
        }
    }

    public function handleEvent($object)
    {
        switch ($object->Event) {
            case "subscribe":
                $account_id = substr(trim($object->EventKey), 8);
                break;
            case "SCAN":
                $account_id = trim($object->EventKey);
                break;
            default :
                $account_id = '';
                break;
        }
        if (empty($account_id)) {
            return false;
        }
        $openid = trim($object->FromUserName);
        return array('openid' => $openid, 'p_id' => $account_id);
//        $resultStr = $this->responseText($object, $contentStr);
//        return $resultStr;
    }

    public function responseText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }

    public function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = '2Cy11gBSwjKLayQNpNge';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function menu()
    {
        $appid = $this->appid;
        $redirect_uri = 'http://fangdichan.whtxcloud.com';
        $jsonmenu = '{
             "button":
             [
                 {    
                      "type":"miniprogram",
                      "name":"拼多多券",
                      "appid":"wx5d513c3ec8919926",
                      "pagepath":"hc_pdd/pages/index/index",
                      "url":"http://www.whtxcloud.com"
                  },
                  {    
                      "type":"view",
                      "name":"金山地产",
                      "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
                  }
              ]
        }';
        $token = $this->get_token();
//        var_dump($token);die;
        if(is_array($token)){
            $token = $token[0];
        }
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $token;
        $result = self::httpRequest($url, $jsonmenu);
        var_dump($result);die;

    }
    //获取签名jssdk
    public function get_ticket($url_a)
    {
        $ticket = UserLogic::get_session('ticket');
        if(!$ticket){
            $token = $this->get_token();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi";
            $result = self::httpRequest($url);
            $res =  json_decode($result,true);
            if (empty($res['ticket'])) {
                return false;
            }
            //换取签名
            $jsapi_ticket = $res['ticket'];
            UserLogic::set_session('ticket',$jsapi_ticket,7200);
        }else{
            $jsapi_ticket = $ticket;
        }
        $timestamp = time();
        $nonceStr = md5($timestamp);
        $url = $url_a;
        $signature = sha1("jsapi_ticket={$jsapi_ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}");
        $appid = $this->appid;
        return array(
            'appid'=>$appid,
            'timestamp'=>$timestamp,
            'nonceStr'=>$nonceStr,
            'signature'=>$signature
        );
    }





















}